<template>
  <el-row>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;height:46px">
      <el-form :inline="true">
        <el-form-item>
          <el-input size="small" v-model="goodsCodeStr" placeholder="商品代码" style="vertical-align:top"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input size="small" v-model="goodsNameStr" placeholder="商品名称" style="vertical-align:top"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search" size="small" style="line-height:14px;vertical-align:top">查询</el-button>
        </el-form-item>
        <el-form-item class="button-align" v-if="getAuth(0)">
          <el-button type="primary" @click="handleAdd" size="small">发布商品</el-button>
        </el-form-item>
        <el-form-item class="button-align">
          <el-button type="danger" @click="batchDelete" :disabled="this.sels.length===0" size="small" v-if="getAuth(1)">批量删除</el-button>
        </el-form-item>
        <el-form-item class="button-align">
          <el-button type="warning" @click="batchStatus(0)" :disabled="this.sels.length===0" size="small" v-if="getAuth(2)">批量下架</el-button>
        </el-form-item>
        <el-form-item class="button-align">
          <el-button type="primary" @click="batchStatus(1)" :disabled="this.sels.length===0" size="small" v-if="getAuth(3)">批量上架</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table border style="width: 100%; font-size: 12px;" :data="retailGoodsList" @selection-change="selsChange" row-class-name="tabRow"
              tooltip-effect="light" v-loading="listLoading">
      <el-table-column type="selection"></el-table-column>
      <el-table-column align="center" prop="goodsGroupName" label="商品分组名称"></el-table-column>
      <el-table-column align="center" label="商品状态" width="90">
        <template scope="scope">
          <el-switch v-model="scope.row.goodsState" on-text="上架" off-text="下架" @change="handleChangeStatus(scope.row)"
                     on-color="#13ce66"
                     off-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="goodsCode" label="商品编码"></el-table-column>
      <el-table-column align="center" prop="goodsName" label="商品名称" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="stocks" label="总库存"></el-table-column>
      <el-table-column align="center" prop="createTime" :formatter="createTimeStr" label="创建时间"></el-table-column>
      <el-table-column align="center" label="操作" width="150px;">
        <template scope="scope">
          <el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)" v-if="getAuth(4)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)" :disabled="scope.row.goodsState" v-if="getAuth(5)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="toolbar" style="margin-top: 15px;" v-show="!listLoading">
      <el-pagination id="pagination" layout="total, sizes, prev, pager, next, jumper" wi :page-sizes="[10, 20, 30]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-size="pageSize" :current-page="page" :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>
  </el-row>
</template>

<script type="text/ecmascript-6">
  import {resetBreads, sessionOut, buttonAuth} from '../../smartlight/common/js/util.js'
  export default{
    data () {
      return {
        total: 2,
        page: 1,
        pageSize: 10,
        retailGoodsList: [],
        count: 0,
        sels: [], // 列表选中列
        showAdd: false,
        loginType: 0,
        loginType1: {
          type: 0
        },
        goodsCodeStr: '',
        goodsNameStr: '',
        listLoading: false,
        retailButtons: [718, 719, 720, 721, 722, 723]
      }
    },
    methods: {
// 权限控制
      getAuth (index) {
        return buttonAuth(index, 1, [], this.retailButtons, [])
      },
      // 分页插件查询方法-条数
      handleSizeChange (val) {
        this.pageSize = val
        this.initRetailGoodsList()
      },
      // 分页插件查询方法-页数
      handleCurrentChange (val) {
        this.page = val
        this.currentPage = val
        this.initRetailGoodsList()
      },
      search () {
        this.page = 1
        this.initRetailGoodsList()
      },
      // 初始化分页查询微信小程序
      initRetailGoodsList () {
        this.listLoading = true
        var para = {
          pageNumber: this.page,
          pageSize: this.pageSize,
          goodsCode: this.goodsCodeStr.trim(),
          goodsName: this.goodsNameStr.trim(),
          companyId: this.companyId,
          type: this.loginType
        }
        this.$http.post('/smartLight/web/retailGoods/getPage.htm', para).then(response => {
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.total = resBody.result.totalElements
            this.retailGoodsList = resBody.result.content
            this.listLoading = false
          } else if (resBody.isSuccess === 2) {
            this.listLoading = false
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      batchStatus (num) {
        var ids = []
        this.sels.map(item => {
          ids.push(item.id)
        })
        let status = false
        if (num === 1) {
          status = true
        }
        this.listLoading = true // 显示等待动画
        var para = {
          type: this.loginType,
          goodsState: status, // 0 批量下架， 1 批量上架
          id: ids.toString()
        }
        this.handleStatus(para)
      },
      // 状态
      handleChangeStatus (row) {
        this.listLoading = true // 显示等待动画
        var para = {
          type: this.loginType,
          goodsState: row.goodsState,
          id: row.id
        }
        this.handleStatus(para)
      },
      handleStatus (para) {
        this.$http.post('/smartLight/web/retailGoods/updateStatus.htm', para).then(response => {
          this.listLoading = false // 隐藏等待动画
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.$message({
              showClose: true,
              message: '操作成功',
              type: 'success'
            })
          } else if (resBody.isSuccess === 2) {
            sessionOut(this) // session超时处理
          } else {
            // 修改失败时状态不变，并提示失败信息
            this.initRetailGoodsList()
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
          this.initRetailGoodsList()
        })
      },
      handleEdit (index, row) {
        this.$router.push({path: '/retailGoodsAdd', query: {ftype: 'edit', id: row.id}})
        this.$store.dispatch('updatelocationpath', '/retailGoodsAdd')
        var breads = this.$store.state.breads
        breads.push('编辑商品')
        this.$store.dispatch('updateBreads', breads)
      },
      handleAdd () {
        this.$router.push({path: '/retailGoodsAdd', query: {ftype: 'add'}})
        this.$store.dispatch('updatelocationpath', '/retailGoodsAdd')
        var breads = this.$store.state.breads
        breads.push('商品发布')
        this.$store.dispatch('updateBreads', breads)
      },
      selsChange: function (sels) {
        this.sels = sels
      },
      // 【删除】按钮事件
      handleDelete (index, row) {
        var ids = []
        ids.push(row.id)
        this.deleteRetailGoods(ids)
      },
      // 【批量删除】按钮事件
      batchDelete () {
        var ids = []
        this.sels.map(item => {
          if (item.goodsState) {
            return
          }
          ids.push(item.id)
        })
        // 删除的Id与被选中的数量不对
        if (ids.length !== this.sels.length) {
          this.$message({
            showClose: true,
            message: '存在上架产品，不予删除',
            type: 'error'
          })
        } else {
          this.deleteRetailGoods(ids)
        }
      },
      // 【删除】、【批量删除】执行方法
      deleteRetailGoods (ids) {
        this.$confirm('确定删除产品吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/smartLight/web/retailGoods/deleteByIds.htm', ids + '|' + this.loginType).then(response => {
            var resBody = response.body
            if (resBody.isSuccess === 0) {
              this.$message({
                showClose: true,
                message: '删除成功',
                type: 'success'
              })
              this.page = 1
              this.initRetailGoodsList()
            } else if (resBody.isSuccess === 2) {
              this.listLoading = false
              sessionOut(this) // session超时处理
            } else {
              this.$message({
                showClose: true,
                message: '删除失败',
                type: 'error'
              })
            }
          })
        }).catch(() => {
        })
      },
      //      时间格式化
      createTimeStr (row, column) {
        var d = new Date(row.createTime)
        var year = d.getFullYear()
        var month = d.getMonth() + 1
        if (month < 10) {
          month = '0' + month
        }
        var date = d.getDate()
        if (date < 10) {
          date = '0' + date
        }
        var hh = d.getHours()
        if (hh < 10) {
          hh = '0' + hh
        }
        var mm = d.getMinutes()
        if (mm < 10) {
          mm = '0' + mm
        }
        var ss = d.getSeconds()
        if (ss < 10) {
          ss = '0' + ss
        }
        return year + '-' + month + '-' + date + ' ' + hh + ':' + mm + ':' + ss
      }
    },
    mounted () {
      var user = sessionStorage.getItem('user')
      if (user) {
        resetBreads(this)
        user = JSON.parse(user)
        this.loginType = user.type
        this.loginType1.type = user.type
        this.initRetailGoodsList()
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  .tabRow
    font-size: 12px;

  .button-align
    float: right;

  .el-dialog--small
    width: 37%;

  .prompt
    color: #ff4949
    line-height: 10px !important;
    display: block;

  .borderStyle
    .el-input .el-input__inner {
      border-color: #ff4949 !important;
    }

  .cell
    padding-left: 0px !important
    padding-right 0px !important
    overflow: hidden !important
    text-overflow: ellipsis !important
    white-space: nowrap !important
    .el-checkbox {
      padding-left: 15px !important
    }
</style>
